<template>
  <div class="order-list">
    <a-card class="order-list-info">
      未发布订单
    </a-card>
    <br>
    <a-card title="详细数据">
      <span slot="extra">
        <a-button
          class="order-list-margin-right"
          @click="getData"
        >拉取数据</a-button>
        <a-button
          type="primary"
          class="order-list-margin-right"
          :disabled="selectOrder.length === 0"
          @click="publishSome"
        >批量发布</a-button>
        <a-button 
          type="danger"
          :disabled="selectOrder.length === 0"
          @click="sendBackSome"
        >批量退回</a-button>
      </span>
      <div style="overflow-x: auto;">
        <a-table 
          row-key="id"
          bordered
          :columns="columns"
          :data-source="data"
          :row-selection="rowSelection"
          :loading="loading"
          :pagination="paginationConfig"
          @change="handleTablePageChange"
        >
          <span slot="user" slot-scope="user">
            {{ user }}
            <a-icon type="right-circle"
                    style="float:right;font-size: 16px;line-height: 25px;"
                    title="点击查看用户所有订单"
                    @click="findUserAllList(user)" />
          </span>
          <span slot="createTime" slot-scope="createTime">{{createTime === null ? '暂无数据' : transformFormatDate(createTime)}}</span>
          <span slot="status" slot-scope="status">{{ status === 0 ? '已下单' : '异常' }}</span>
          <span slot="operation"
                slot-scope="scope">
            <span v-if="searchInfo.searchType === '1'">
              <a-popconfirm
                title="确定将这条订单发布吗?"
                ok-text="确定"
                cancel-text="取消"
                @confirm="confirmPublish(scope)"
                @cancel="() => {$message.warn('取消发布')}"
              >
                <a-button type="primary" size="small" class="order-list-margin-right">发布</a-button>
              </a-popconfirm>
              <a-popconfirm
                title="确定将这条订单退回吗?"
                ok-text="确定"
                cancel-text="取消"
                @confirm="confirmSendBack(scope)"
                @cancel="() => {$message.warn('取消退回')}"
              >
                <a-button type="danger" size="small">退回</a-button>
              </a-popconfirm>
            </span>
            <span v-else-if="searchInfo.searchType === '2'">
              <a-popconfirm
                  title="确定将这条订单退回吗?"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="confirmSendBack(scope)"
                  @cancel="() => {$message.warn('取消退回')}">
                <a-button type="danger" size="small">退回</a-button>
              </a-popconfirm>
            </span>
            <span v-else-if="searchInfo.searchType === '0'">
              <a-popconfirm
                  title="确定将这条订单发布吗?"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="confirmPublish(scope)"
                  @cancel="() => {$message.warn('取消发布')}">
                <a-button type="primary" size="small">发布</a-button>
              </a-popconfirm>
            </span>
<!--            <span v-show="searchInfo.searchType === '3'">-->
<!--              <a-button type="primary" size="small">查看进度</a-button>-->
<!--            </span>-->
            <span v-else-if="searchInfo.searchType === '6'">
              <a-button type="primary"
                        size="small"
                        @click="viewRecord(scope)">查看流水</a-button>
            </span>
            <span v-else-if="searchInfo.searchType === '-1'">
              <a-popconfirm
                  title="确定将这条订单发布吗?"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="confirmPublish(scope)"
                  @cancel="() => {$message.warn('取消回滚')}">
                <a-button type="primary" size="small">回滚订单</a-button>
              </a-popconfirm>
            </span>
            <span v-else>
              <a-button type="primary" disabled>不可操作</a-button>
            </span>
          </span>
        </a-table>
      </div>
    </a-card>
    <!-- code=6查看流水 -->
    <a-drawer title="查看流水"
              placement="right"
              width="400"
              @close="drawerVisible = false"
              :visible="drawerVisible">
      <div v-if="viewRecordList && viewRecordList.length !== 0">
        <div style="font-size: 18px;font-weight: bold;margin: 8px 0;">订单情况: </div>
          <div>
            用户是否撤单:
            <a-tag :color="viewRecordList.codeZero === null ? '#2db7f5' : '#e01212'">
              {{ viewRecordList.codeZero === null ? '否' : '是' }}
            </a-tag>
          </div>
        <br>
          <div>
            用户是否退单:
            <a-tag :color="viewRecordList.codeBackFirst === null ? '#2db7f5' : '#e01212'">
              {{ viewRecordList.codeBackFirst === null ? '否' : '是' }}
            </a-tag>
          </div>
        <div style="font-size: 18px;font-weight: bold;margin: 8px 0;">流水: </div>
        <a-timeline>
          <a-timeline-item>
            {{ transformFormatDate(viewRecordList.codeFirst) }}
            <div>用户下订单</div>
          </a-timeline-item>
          <a-timeline-item>
            {{ transformFormatDate(viewRecordList.codeSecond) }}
            <div>订单审核通过</div>
          </a-timeline-item>
          <a-timeline-item>
            {{ transformFormatDate(viewRecordList.codeThird) }}
            <div>维修人员接单</div>
          </a-timeline-item>
          <a-timeline-item>
            {{ transformFormatDate(viewRecordList.codeForth) }}
            <div>维修完成报价</div>
          </a-timeline-item>
          <a-timeline-item>
            {{ transformFormatDate(viewRecordList.codeFifth) }}
            <div>订单支付完成</div>
          </a-timeline-item>
          <a-timeline-item>
            {{ transformFormatDate(viewRecordList.codeSixth) }}
            <div>订单评价完成</div>
          </a-timeline-item>
        </a-timeline>
      </div>
      <a-empty v-else />
    </a-drawer>
  </div>
</template>

<script>
  import { formatDate } from '@/lib/common';
  import { getOrderList, changeOrderStatus, getViewRecord, searchOrderNumber, makeOrderEffective, makeOrderIneffective } from "@/api/api";

  export default {
    name: "OrderList",
    data() {
      const rowSelection = {
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectOrder = selectedRowKeys;
        },
      };
      return {
        dateFormat: 'YYYY-MM-DD HH:mm',
        todayDate: [
          new Date(new Date(new Date().toLocaleDateString()).getTime()),
          new Date(new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 *60 * 1000)
        ],
        searchInfo: {
          searchType: '1',
          searchDate: [new Date(new Date().toLocaleDateString()).getTime(),
            new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 *60 * 1000],
        },
        columns: [
          {title: '订单编号', dataIndex: 'orderNumber'},
          {title: '描述信息', dataIndex: 'desc'},
          {title: '创建时间', dataIndex: 'createTime', scopedSlots: {customRender: 'createTime'}, width: 200},
          // {title: '服务时间', dataIndex: 'serverTime', scopedSlots: {customRender: 'serverTime'}, width: 200},
          // {title: '结束时间', dataIndex: 'finishTime', scopedSlots: {customRender: 'finishTime'}, width: 200},
          // {title: '评价', dataIndex: 'evaluation'},
          {title: '订单状态', dataIndex: 'status', scopedSlots: {customRender: 'status'}},
          {title: '用户姓名', dataIndex: 'userInfo.name'},
          {title: '用户地址', dataIndex: 'userInfo.userAddress'},
          // {title: '估计价格', dataIndex: 'probablyPrice', scopedSlots: {customRender: 'evaluatePrice'}, width: 100},
          // {title: '最终价格', dataIndex: 'finalPrice', scopedSlots: {customRender: 'finalPrice'}, width: 100},
          // {title: '服务状态', dataIndex: 'code'},
          // {title: '服务时间', dataIndex: 'serverTime', scopedSlots: {customRender: 'serverTime'}, width: 160},
          // {title: '服务评价', dataIndex: 'evaluation', scopedSlots: {customRender: 'serverRate'}, ellipsis: true},
          // {title: '是否撤单', dataIndex: 'undoOrder'},
          // {title: '是否退单', dataIndex: 'chargeBack'},
          // {title: '图片描述', dataIndex: 'pic'},
          {title: '操作', key: 'operation', width: 150, scopedSlots: { customRender: 'operation' }},
        ],
        data: [],
        paginationConfig: {
          total: 1,
          pageSize: 10,
          current: 1
        },
        rowSelection,
        loading: false,
        mulSelect: [],
        searchOrderNumber: '',
        drawerVisible: false,
        viewRecordList: {},
        selectOrder: [],
      }
    },
    methods: {
      /**
       * 时间戳转换为日期
       * @param data 时间戳
       */
      transformFormatDate(data) {
        return formatDate(parseInt(data));
      },
      /**
       * 拉取数据
       */
      getData() {
        this.paginationConfig.current = 1;
        this.loadOrderList();
      },
      /**
       * 表格页码切换方法
       * @param pagination
       * @param filters
       * @param sorter
       * @param currentDataSource
       */
      handleTablePageChange(pagination, filters, sorter, { currentDataSource }) {
        this.paginationConfig.current = pagination.current;
        this.loadOrderList();
      },
      /**
       * 类型选择框改变方法
       * @param value 改变后对应的value值
       */
      handleSelectChange(value) {
        this.searchInfo.searchType = value;
        this.loadOrderList();
      },
      /**
       * 日期时间选择框数据改变点击确定时的方法
       * @param dates 日期（moment格式）
       */
      onDateChange(dates) {
        this.searchInfo.searchDate = [new Date(dates[0]._d).getTime(), new Date(dates[1]._d).getTime()];
      },
      /**
       * 确认发布订单
       */
      confirmPublish(row) {
        changeOrderStatus({ id: row.id, status: 1 })
          .then(res => {
            this.$message.success('发布成功');
            this.loadOrderList();
          })
          .catch(err => {
            this.$message.error(`发布失败,${err.data}`);
          })
      },
      /**
       * 批量发布订单
       */
      publishSome() {
        for (let i = 0; i < this.selectOrder.length; i++) {
          new Promise((resolve, reject) => {
            changeOrderStatus({ id: this.selectOrder[i], status: 1 })
            .then(() => { resolve() })
            .catch(() => { reject('error') })
          })
          .then(() => { i++; })
          .catch((err) => { return console.log(err); })
        }
        this.$nextTick(() => {
          this.$message.success('操作成功');
          this.selectOrder = [];
          this.loadOrderList();
        })
      },
      /**
       * 确认退回订单
       */
      confirmSendBack(row) {
        changeOrderStatus({ id: row.id, status: -1 })
          .then(res => {
            this.$message.success('退回成功');
            this.loadOrderList();
          })
          .catch(err => {
            this.$message.error(`退回失败,${err.data}`);
          })
      },
      /**
       * 批量回退订单
       */
      sendBackSome() {
        for (let i = 0; i < this.selectOrder.length; i++) {
          new Promise((resolve, reject) => {
            changeOrderStatus({ id: this.selectOrder[i], status: -1 })
            .then(() => { resolve() })
            .catch(() => { reject() })
          })
          .then(res => { i++; })
          .catch(err => { console.log(err); })
        }
        this.$nextTick(() => {
          this.$message.success('操作成功');
          this.selectOrder = [];
          this.loadOrderList();
        })
      },
      /**
       * 通过订单编号查询数据
       */
      searchOrderList() {
        if (this.searchOrderNumber === '') {
          // this.loadOrderList();
        }else {
          searchOrderNumber({ orderNumber: this.searchOrderNumber })
              .then(res => {
                console.log(res);
                let newData = [];
                if (res.data !== null) {
                  newData.push(res.data);
                  for (let i in newData) {
                    newData[i].key = i;
                  }
                }
                this.data = newData;
                this.$message.success('查询成功');
              })
              .catch(err => {
                this.$message.error(`查询失败，错误信息${err}`);
              })
        }
      },
      /**
       * 获取表格数据
       */
      loadOrderList() {
        this.loading = true;
        let options = {
          page: this.paginationConfig.current,
          size: this.paginationConfig.pageSize,
          orderNumber: '',
          startTime: '',
          endTime: '',
          evaluation: '',
          status: 0
        };
        getOrderList(options)
          .then(res => {
            let data = res.data;
            this.data = data.list;
            this.paginationConfig.total = data.total;
          })
          .catch(err =>{
            this.$message.error(err);
          })
          .finally(() => {
            this.loading = false;
          })
      },
      /**
       * 查看流水
       */
      viewRecord(row) {
        this.drawerVisible = true;
        getViewRecord({ id: row.id })
          .then(res => {
            this.viewRecordList = res.data;
          })
          .catch(err => {
            this.$message.error(err);
          })
      },
      /**
       * 查看用户所有订单
       */
      findUserAllList(user) {
        this.$bus.$emit('findUserAllList', user);
        this.$router.push('/home/all-list');
      }
    },
    mounted() {
      this.loadOrderList();
    }
  }
</script>

<style lang="scss">
.order-list {
  .order-list-margin-right {
    margin-right: 10px;
  }
}
</style>